<template>
  <el-dialog :title="title" :visible.sync="dialogVisible" :before-close="handleClose" width="1000" :close-on-click-modal="false">
    <div class="fr">
      <el-form :inline="true" :model="formInline" class="">
        <el-form-item label="关键词" prop="keyword">
          <el-input v-model="formInline.keyword" clearable placeholder="请输入" size="small"></el-input>
        </el-form-item>
        <el-form-item label="文件编码" prop="fileCode">
          <el-input v-model="formInline.fileCode" clearable placeholder="请输入" size="small"></el-input>
        </el-form-item>
        <el-form-item label="文件版本" prop="fileVersion">
          <el-input v-model="formInline.fileVersion" clearable placeholder="请输入" size="small"></el-input>
        </el-form-item>
        <el-form-item label="条款编码" prop="provisionCode">
          <el-input v-model="formInline.provisionCode" clearable placeholder="请输入" size="small"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch" size="small">搜索</el-button>
          <el-button type="primary" plain @click="handleReset" size="small">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    <el-table v-loading="loading" :data="tableData"  ref="tableRef" @selection-change="selectionChange">
      <el-table-column type="selection" width="50"></el-table-column>
      <el-table-column label="序号" type="index" width="50" :index="indexMethod">
      </el-table-column>
      <el-table-column prop="fileCode" label="文件编码"> </el-table-column>
      <el-table-column prop="fileName" label="文件名称"> </el-table-column>
      <el-table-column prop="fileVersion" label="文件版本" />
      <el-table-column prop="provisionCode" label="条款编码" />
      <el-table-column prop="provisionContent" label="条款内容" />
    </el-table>

    <el-pagination class="p20 fr" v-if="total > 0" :background="true" :current-page.sync="queryParams.pageNum"
      :page-size.sync="queryParams.pageSize" :layout="'total, sizes, prev, pager, next, jumper'"
      :page-sizes="[10, 30, 50, 100]" :total="total" @size-change="handleSizeChange"
      @current-change="handlepageNumChange" />
    <span slot="footer" class="dialog-footer">
      <el-button size="mini" @click="handleClose">取 消</el-button>
      <el-button size="mini" type="primary" @click="handleConfirm">确 定</el-button>
    </span>
  </el-dialog>
</template>

<script>
import { v4 as uuid } from 'uuid';
import tinymce from "tinymce/tinymce";
import { getProvisionList } from "@/api/clauseLibrary";
import { saveVeriableValue } from '@/api/computingConfig.js'
export default {
  name: "ProvisionRepalceDialog",
  data() {
    return {
      title: '选择条款',
      dialogVisible: false,
      formInline: {
        keyword: "",
        fileCode: "",
        fileVersion: '',
        provisionCode: ''
      },
      queryParams: {
        pageNum: 1,
        pageSize: 10,
      },
      loading: false,
      total: 0,
      tableData: [],
      selectionListAll: [],
      allVariables:[],
      selectionList:[],
      selectionListAll:[],
      idKey:"id"
    };
  },
  mounted() {
    this.handleSearch();
  },
  methods: {
    show() {
      this.dialogVisible = true;
    },
    handleClose() {
      this.dialogVisible = false;
    },
    handleConfirm() {
      if (!this.selectionListAll.length) {
        return this.$message.warning('请选择数据！')
      }
      this.$store.commit('xmleditor/SET_PROVISION_SELECTIONS', this.selectionListAll)
      const tableTitles = ['序号', '条款', '条款要求', '符合性说明']
      const tableAttrs = ['index', 'provisionCode', 'provisionContent', 'provisionDescribe']
      const tableDatas = this.selectionListAll.map((item, index) => {
        item.index = index + 1
        return item
      })
      const tableId = this.$store.state.xmleditor.variableTableDataId;
      const doc = tinymce.activeEditor.getDoc();
      if (tableId?.dataId) {
        
        const nodes = doc.querySelector(`[data-id="${tableId?.dataId}"]`)
        const tableChildren = nodes.childNodes;
        tableChildren.forEach(el => {
          if (el.nodeName == 'CAPTION') {
            this.caption = el.innerHTML;
          }
          // 表头设置
          if (el.nodeName == 'THEAD') {
            let tr = '';
            if (tableTitles.length > 0) {
              tableTitles.forEach(title => {
                let th = '';
                th = `<th colspan="1" rowspan="1" data-id="${uuid()}">
		                    <p data-type="paragraph" data-lang="zh">${title}​</p>
	                    </th>`
                tr += th;
              })
              tr = `<tr data-id="${uuid()}">${tr}</tr>`
            }
            el.innerHTML = tr
          }
          // 数据设置
          if (el.nodeName == 'TBODY') {
            let tbody = '';
            if (tableDatas.length > 0) {
              tableDatas.forEach((dataItem, index) => {
                let tr = '';
                tableAttrs.forEach((tdData,index) => {
                  let td = '';
                  if(index==2){
                    td = `<td colspan="1" rowspan="1" data-id="${uuid()}">
		                    <p data-type="paragraph" data-lang="zh" style="text-align:left;">${dataItem[tdData] || ''}​</p>
	                    </td>`
                  }else{
                    td = `<td colspan="1" rowspan="1" data-id="${uuid()}">
		                    <p data-type="paragraph" data-lang="zh">${dataItem[tdData] || ''}​</p>
	                    </td>`
                  }
                 
                  tr += td;
                })
                tbody += `<tr data-id="${uuid()}">${tr}</tr>`
              })

            }
            el.innerHTML = tbody
          }
        })
      }
      // 保存变量值
      const variableContent = {
        columns: tableAttrs,
        titles: tableTitles,
        data: this.selectionListAll
      }
      const formData = new FormData();
      formData.append("docNo", this.$store.state.xmleditor.docInfo.docNo);
      formData.append("id", Number.parseInt(tableId?.variableId));
      formData.append("variableContent", JSON.stringify(variableContent));
      saveVeriableValue(formData);
      // 设置条款名称字符串
      let contentValue = ''
      this.selectionListAll.forEach(item=>{
        contentValue+=`${item.provisionCode},`
      });
      this.allVariables = this.$store.state.xmleditor.allVariableContent;
      const provisionVariableId = this.allVariables.filter(el=>{
        return el.variableCode =='provision.codes'
      })
      const provisionVariableNode = doc.querySelectorAll(`[data-variable-id="${provisionVariableId[0]?.id}"]`);
      provisionVariableNode.forEach(item=>{
        item.innerText = contentValue;
      })
      
     
      this.dialogVisible = false;
    },
    indexMethod(index) {
      return (
        (this.queryParams.pageNum - 1) * this.queryParams.pageSize + index + 1
      );
    },
    async onSearch() {
      try {
        this.loading = true;
        const res = await getProvisionList({
          ...this.queryParams,
          ...this.formInline,
        });
        this.tableData = res.data.list;
        this.total = res.data.count;
        this.$nextTick(()=>{
          this.setSelectRow();
        })
      } catch (error) {
        console.log(error);
      } finally {
        this.loading = false;
      }
    },
    handleReset() {
      this.formInline = {
        keyword: "",
        fileCode: "",
        fileVersion: '',
        provisionCode: ''
      };
      this.onSearch();
    },
    handleSearch() {
      this.queryParams.pageNum = 1;
      this.onSearch();
    },
    handleSizeChange(val) {
      if (this.queryParams.pageSize * val > this.total) {
        this.queryParams.pageNum = 1;
      }
      this.onSearch();
    },
    handlepageNumChange() {
      this.onSearch();
    },
    handleSelectionChange(val) {
      this.selectionListAll = val
    },
    selectionChange (val) {
      // 表格选项发生变化
      this.selectionList = val
      this.$nextTick(() => {
        this.changePageCoreRecordData()
      })
    },
    // 记忆选择核心方法
    changePageCoreRecordData () {
      // 标识当前行的唯一键的名称
      const idKey = this.idKey
      const that = this
      // 如果总记忆中还没有选择的数据，那么就直接取当前页选中的数据，不需要后面一系列计算
      if (this.selectionListAll.length <= 0) {
        this.selectionListAll = this.selectionList
        return
      }
      // 总选择里面的key集合
      const selectAllIds = []
      this.selectionListAll.forEach(row => {
        selectAllIds.push(row[idKey])
      })
      const selectIds = []
      // 获取当前页选中的id
      this.selectionList.forEach(row => {
        selectIds.push(row[idKey])
        // 如果总选择里面不包含当前页选中的数据，那么就加入到总选择集合里
        if (selectAllIds.indexOf(row[idKey]) < 0) {
          that.selectionListAll.push(row)
        }
      })
      const noSelectIds = []
      // 得到当前页没有选中的id
      this.tableData.forEach(row => {
        if (selectIds.indexOf(row[idKey]) < 0) {
          noSelectIds.push(row[idKey])
        }
      })
      noSelectIds.forEach(id => {
        if (selectAllIds.indexOf(id) >= 0) {
          for (let i = 0; i < that.selectionListAll.length; i++) {
            if (that.selectionListAll[i][idKey] == id) {
              // 如果总选择中有未被选中的，那么就删除这条
              that.selectionListAll.splice(i, 1)
              break
            }
          }
        }
      })
    },
    // 设置选中的方法
    setSelectRow () {
      if (!this.selectionListAll || this.selectionListAll.length <= 0) {
        return
      }
      // 标识当前行的唯一键的名称
      const idKey = this.idKey
      const selectAllIds = []
      this.selectionListAll.forEach(row => {
        selectAllIds.push(row[idKey])
      })
      this.$refs.tableRef.clearSelection()
      for (var i = 0; i < this.tableData.length; i++) {
        if (selectAllIds.indexOf(this.tableData[i][idKey]) >= 0) {
          // 设置选中，记住table组件需要使用ref="table"
          this.$refs.tableRef.toggleRowSelection(this.tableData[i], true)
        }
      }
    }
  }
}
</script>

<style scoped></style>